package git.soulbgm.service;

import git.soulbgm.mapper.MessageMapper;
import git.soulbgm.pojo.Message;
import git.soulbgm.utils.DateUtil;
import git.soulbgm.utils.LogUtil;
import git.soulbgm.utils.SequenceBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Service
public class MessageService {

    @Resource
    private MessageMapper mapper;

    @Async
    public Future<Integer> insertList(int totalNum, int cycleNum, Calendar c, CountDownLatch latch) {
//        int totalNum = 80000000;
//        int cycleNum1 = 20000;
        int cycleNum2 = totalNum / cycleNum;
        int totalResult = 0;
        for (int i = 0; i < cycleNum; i++) {
            List<Message> messages = new ArrayList<>(cycleNum2);
            for (int d = 0; d < cycleNum2; d++) {
                Message message = getMessage();
                message.setId(SequenceBuilder.sequenceId() + "");
                message.setStoreTime(c.getTimeInMillis());
                message.setPackageTime(c.getTimeInMillis());
                message.setServerTime(c.getTimeInMillis());
                messages.add(message);
            }
            int result = mapper.upsertList(messages);
            totalResult += result;
        }
        latch.countDown();
        return new AsyncResult<>(totalResult);
    }

    @Async
    public Future<List<Message>> insertList(int totalNum, Calendar c) {
        List<Message> messages = new ArrayList<>(totalNum);
        for (int i = 0; i < totalNum; i++) {
            Message message = getMessage();
            message.setId(SequenceBuilder.sequenceId() + "");
            message.setStoreTime(c.getTimeInMillis());
            message.setPackageTime(c.getTimeInMillis());
            message.setServerTime(c.getTimeInMillis());
            messages.add(message);
        }
        int result = mapper.upsertList(messages);
        return new AsyncResult<>(messages);
    }

    public List<Message> findByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    private Message getMessage() {
        Message message = new Message();
        message.setAnalysisInfo("{\"测试性能\":0,\"处理结果\":1,\"s\":1,\"M\":1,\"H\":1,\"收方地址\":7000379,\"发方地址\":7000379,\"发方类型\":1,\"信息编号\":1}");
        message.setSourceId(1010);
        message.setSourceType(1010);
        message.setMsgType(1010);
        message.setSbdCard("1010");
        message.setRbdCard("1010");
        message.setPosition("1010");
        return message;
    }


}
